import React, { useState, useEffect, FC, useRef } from 'react'
import {
  Row, Col, Card,
  Space,
  Modal,
  Table,
  Spin,
  TimePicker
} from 'antd'
import moment from 'moment'
import type { Moment } from 'moment'
import type { ColumnsType, ColumnType } from 'antd/es/table'
import XlButtonFC from '@/components/xlbutton/xlbutton'
import { BaseOptionType } from 'antd/lib/select'
import XlModalFC from '@/components/xlmodal/xlmodal'
import { IBackupStatusModel, IData, IResponseCodeType } from '@/models/common'
import util from '@/utils/util'
import * as api from '@/api'
import "./backupschedule.scss"
export interface IViewModel {
  pageLoading: boolean
  backup_list_oss: BaseOptionType[]
  backup_list_local: BaseOptionType[]
  backup_plantime: BaseOptionType[]
  backup_plan: string
  backup_status: string
  oss_status: string
  setPlanModalOpen: boolean
  format: string
  notAuth: boolean
}
const BackupSchedule: FC = () => {

  const [data, setData] = useState<IData<IViewModel>>({
    ViewModel: {
      pageLoading: false,
      backup_list_oss: [],
      backup_list_local: [],
      backup_status: "",
      backup_plan: "",
      oss_status: "",
      setPlanModalOpen: false,
      backup_plantime: [{
        time: "",
        id: util.getGuid(),
      }],
      format: "HH:mm",
      notAuth: false
    }
  })

  useEffect(() => {
    
  }, [])

  const events = {
    onClickStartBackup() {
      Modal.confirm({
        title: '备份',
        centered: true,
        closable: true,
        content: '确认立即备份吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestSystemBackup()
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickSetting() {
      const { ViewModel } = data
      ViewModel.setPlanModalOpen = true
      setData({ ...data })
    },
    onSetPlanOk() {
      const { ViewModel } = data
      const { backup_plantime, format } = ViewModel
      let isHasEmpty = false
      let plan = []
      for (let i = 0; i < backup_plantime.length; i++) {
        const o = backup_plantime[i];
        if (!o.time) {
          isHasEmpty = true
          break
        }
        if (typeof (o.time) == 'object') {
          let time = moment(o.time).format(format)
          plan.push(time)
        }
      }
      // console.log(backup_plantime, ViewModel.backup_plantime);
      if (isHasEmpty || plan.length == 0) {
        util.alertTip('备份时间不能为空')
        return
      }
      const plan_json = {
        type: "day",
        value: plan.join(",")
      }
      methods.requestSetBackupPlan(JSON.stringify(plan_json))
    },
    onSetPlanCancel() {
      const { ViewModel } = data
      ViewModel.setPlanModalOpen = false
      setData({ ...data })
    },
    // 还原备份
    onClickRestoreBackup(_: BaseOptionType, record: BaseOptionType, index: number, store_type: string) {
      Modal.confirm({
        title: '还原',
        centered: true,
        closable: true,
        content: '确认还原该备份吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            await methods.requestSystemRestore(record.name, store_type)
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickDeleteBackupPlan(_: BaseOptionType, record: BaseOptionType, index: number) {
      Modal.confirm({
        title: '删除',
        centered: true,
        closable: true,
        content: '确认删除该备份计划吗？',
        onOk() {
          return new Promise(async (resolve, reject) => {
            const { ViewModel } = data
            const { backup_plantime } = ViewModel
            backup_plantime.splice(index, 1)
            ViewModel.backup_plantime = [...backup_plantime]
            setData({ ...data })
            resolve(null)
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {

        },
      })
    },
    onClickAddBackupPlan() {
      const { ViewModel } = data
      const { backup_plantime } = ViewModel
      backup_plantime.push({
        time: "",
        id: util.getGuid()
      })
      ViewModel.backup_plantime = [...backup_plantime]
      setData({ ...data })
    },
    onTimeChange(time: Moment | null, index: number) {
      const { ViewModel } = data
      const { backup_plantime } = ViewModel
      let plantime = backup_plantime[index]
      plantime.time = time
      ViewModel.backup_plantime = [...backup_plantime]
      setData({ ...data })
    },
  }

  const methods = {
    async requestBackupStatus() {
      const { ViewModel } = data
      ViewModel.pageLoading = true
      setData({ ...data })
      let res = await api.common.getBackupStatus<IBackupStatusModel>(null)
      const { code, data: BackupStatusData, message } = res
      if (code == IResponseCodeType.Success) {
        let { backup_list, backup_plan, backup_status, oss_status } = BackupStatusData
        ViewModel.backup_list_local = backup_list.local
        ViewModel.backup_list_oss = backup_list.oss
        ViewModel.backup_plan = backup_plan
        ViewModel.backup_status = backup_status
        ViewModel.oss_status = oss_status
      } else if (code == IResponseCodeType.NotAuth) {
        ViewModel.notAuth = true
      } else {
        util.alertTip(message)
      }
      ViewModel.pageLoading = false
      setData({ ...data })
    },
    async requestSetBackupPlan(plan_json: string) {
      let res = await api.common.setBackupPlan<null>({
        plan_json
      })
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        events.onSetPlanCancel()
        methods.requestBackupStatus()
      }
    },
    async requestSystemRestore(store_name: string, store_type: string) {
      let res = await api.common.systemRestore<null>({
        store_name,
        store_type
      })
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        // methods.requestBackupStatus()
      }
    },
    async requestSystemBackup() {
      let res = await api.common.systemBackup<null>(null)
      const { code, message } = res
      util.alertTip(message)
      if (code == IResponseCodeType.Success) {
        methods.requestBackupStatus()
      }
    },
    createBackupColumns(store_type: string) {
      const columns: ColumnsType<BaseOptionType> = [
        {
          title: '备份时间',
          align: "left",
          key: 'name',
          dataIndex: 'name',
        },
        {
          title: '状态',
          align: "left",
          key: 'status',
          dataIndex: 'status',
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={10}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickRestoreBackup(_, record, index, store_type)}>
                还原
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    createBackupPlanColumns() {
      const columns: ColumnsType<BaseOptionType> = [
        {
          title: '备份时间',
          align: "left",
          key: 'time',
          dataIndex: 'time',
          render: (_, record, index) => (
            <TimePicker inputReadOnly value={record.time ? moment(record.time, data.ViewModel.format) : null} format={data.ViewModel.format} onChange={(time) => events.onTimeChange(time, index)} />
          ),
        },
        {
          title: '操作',
          align: "center",
          key: 'action',
          render: (_, record, index) => (
            <Space size={10}>
              <XlButtonFC type='primary' size='small' onClick={() => events.onClickDeleteBackupPlan(_, record, index)}>
                删除
              </XlButtonFC>
            </Space>
          ),
        }
      ]
      return columns
    },
    renderPage() {
      if (data.ViewModel.notAuth) {
        return null
      }
      return <>
        <Spin spinning={data.ViewModel.pageLoading}>
          <Card title='备份'>
            <Row gutter={[0, 16]} className="backupschedule-card-wrapper">
              <Col span={24}>
                <Card title='备份计划' extra={<Space size={10}>
                  <XlButtonFC type='primary' onClick={() => events.onClickStartBackup()}>
                    立即备份
                  </XlButtonFC>
                  <XlButtonFC type='primary' onClick={() => events.onClickSetting()}>
                    设置
                  </XlButtonFC>
                </Space>}>
                  <Col className='backup-content'>
                    <Row align='middle' className='backup-item' wrap>
                      <Col className='text'>频率：</Col>
                      <Col className='value'>{data.ViewModel.backup_plan}</Col>
                    </Row>
                    <Row align='middle' className='backup-item' wrap>
                      <Col className='text'>状态：</Col>
                      <Col className='value'>{data.ViewModel.backup_status}</Col>
                    </Row>
                    <Row align='middle' className='backup-item' wrap>
                      <Col className='text'>云备份：</Col>
                      <Col className='value'>{data.ViewModel.oss_status}</Col>
                    </Row>
                  </Col>
                </Card>
              </Col>
              <Col span={24}>
                <Card title='本地备份'>
                  <Table
                    rowKey='name'
                    bordered
                    pagination={false}
                    columns={methods.createBackupColumns('local')}
                    dataSource={data.ViewModel.backup_list_local}
                  />
                </Card>
              </Col>
              <Col span={24}>
                <Card title="云备份">
                  <Table
                    rowKey='name'
                    bordered
                    pagination={false}
                    columns={methods.createBackupColumns('oss')}
                    dataSource={data.ViewModel.backup_list_oss}
                  />
                </Card>
              </Col>

            </Row>
          </Card>
        </Spin>
        {/* 设置备份计划弹出框 */}
        <XlModalFC
          open={data.ViewModel.setPlanModalOpen}
          onOk={events.onSetPlanOk}
          onCancel={events.onSetPlanCancel}
          title='设置备份计划'
          destroyOnClose
        >
          <Card bordered={false} className='backupCardSetPlanModal' title={<XlButtonFC type='primary' onClick={() => events.onClickAddBackupPlan()}>
            添加
          </XlButtonFC>}>
            <Table
              rowKey='id'
              bordered
              pagination={false}
              columns={methods.createBackupPlanColumns()}
              dataSource={data.ViewModel.backup_plantime}
              scroll={{
                y: 250
              }}
            />
          </Card>
        </XlModalFC>
      </>
    }
  }
  return methods.renderPage()
}
export default BackupSchedule
